package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.WorkOrderTDao;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.dto.response.DictionariesTree;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.DictionariesTService;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.tree.TreeUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


//字典项接口实现类
@Service("DictionariesTService")
public class DictionariesTServiceImpl implements DictionariesTService {

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Autowired
	private DictionariesTDao dictionariesTDao;
	@Resource
	private RedisClientUtils redisClientUtils;
	@Resource
	private WorkOrderTDao workOrderTDao;

	private static final String REQUIRED="Required";

	//获取出行类型字典项
	@Transactional
	@Override
	public ModelAndView getGoOutTypeList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			List<Map<String,Object>> goOutTypeList = dictionariesTDao.getGoOutTypeList();
			Map<String,Object> returnMap = new HashMap<>();
			returnMap.put("goOutTypeList",goOutTypeList);
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",returnMap);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}


	//区域工程师远程解决时获取字典项
	@Transactional
	@Override
	public ModelAndView getDictionariesTDataByAreaEngineer(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			List<Map<String,Object>> problemLevelList = dictionariesTDao.getProblemLevelList();
			List<Map<String,Object>> userActionList = dictionariesTDao.getUserActionList();
			List<Map<String,Object>> InvalidModelList = dictionariesTDao.getInvalidModelList();
			String dTableName = "serviceNatureDealer";
            if(map.containsKey("orderId") && null != MapUtils.getLong(map,"orderId")){
				WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(MapUtils.getLong(map,"orderId"));
				if(null != workOrderT && StringUtils.isNotBlank(workOrderT.getBookkeepingType())){
					dTableName = "serviceNature";
				}
			}
			List<Map<String,Object>> serviceNatureList = dictionariesTDao.getDictionariesListByDTableName(dTableName);
			Map<String,Object> returnMap = new HashMap<>();
			returnMap.put("problemLevelList",problemLevelList);
			returnMap.put("userActionList",userActionList);
			returnMap.put("InvalidModelList",InvalidModelList);
			returnMap.put("serviceNatureList",serviceNatureList);
			obj.put("status","0");
			obj.put("msg","success");
			obj.put("data",returnMap);
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);	
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}

	@Override
	public void getDictionaryList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		String type = MapUtils.getString(map,"type");
		if(StringUtils.isEmpty(type)){
			ParameterTool.writeErrorResponse(response,-5);
		}
		List<Map<String,Object>> list = getAllDictionaryList();
		Map<String,Object> data = new HashMap<>();
		if(CollectionUtils.isNotEmpty(list)){
			List<Map<String,Object>> resultList = new ArrayList<>();
			for(Map<String,Object> dMap : list){
				String tableName = MapUtils.getString(dMap,"DTableName");
				if(type.equals(tableName)){
					Map<String,Object> tableMap = new HashMap<>();
					tableMap.put("ID",MapUtils.getInteger(dMap,"ID"));
					tableMap.put("DInt",MapUtils.getInteger(dMap,"DInt"));
					tableMap.put("DValue",MapUtils.getString(dMap,"DValue"));
					resultList.add(tableMap);
				}
			}
			if(CollectionUtils.isNotEmpty(resultList)){
				data.put("dictionaryList",resultList);
				ParameterTool.writeSuccessResponse(response,data);
			}else{
				ParameterTool.writeResponse(response,1,"查无字典项");
			}
		}
	}

	@Override
	public void getDictionaryListByDTableName(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		String dTableName = MapUtils.getString(map,"dTableName");
		if(StringUtils.isEmpty(dTableName)){
			ParameterTool.writeErrorResponse(response,-5);
		}
		List<Map<String,Object>> list = dictionariesTDao.getDictionariesListByDTableName(dTableName);
		ParameterTool.writeSuccessResponse(response,list);
	}

	@Override
	public List<Map<String, Object>> getDictionaryList(String type) {
		List<Map<String,Object>> resultList = new ArrayList<>();
		List<Map<String,Object>> list = getAllDictionaryList();
		if(CollectionUtils.isNotEmpty(list)){
			for(Map<String,Object> dMap : list){
				String tableName = MapUtils.getString(dMap,"DTableName");
				if(type.equals(tableName)){
					resultList.add(dMap);
				}
			}
		}
		return resultList;
	}

	@Override
	public String getDictionaryDIntByDValue(String type, String dValue) {
		List<Map<String,Object>> list = getAllDictionaryList();
		if(CollectionUtils.isNotEmpty(list)){
			for(Map<String,Object> dMap : list){
				String tableName = MapUtils.getString(dMap,"DTableName");
				String dValues = MapUtils.getString(dMap,"DValue");
				if(type.equals(tableName) && dValue.equals(dValues)){
					return MapUtils.getString(dMap,"DInt");
				}
			}
		}
		return null;
	}

	@Override
	public String getDictionaryDValueByDInt(String type, Integer dInt) {
		List<Map<String,Object>> list = getAllDictionaryList();
		if(CollectionUtils.isNotEmpty(list)){
			for(Map<String,Object> dMap : list){
				String tableName = MapUtils.getString(dMap,"DTableName");
				Integer dInt1 = MapUtils.getInteger(dMap,"DInt");
				if(type.equals(tableName) && dInt1.equals(dInt)){
					return MapUtils.getString(dMap,"DValue");
				}
			}
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getDictionaryRemark(String type, String remark) {
		List<Map<String,Object>> list = getAllDictionaryList();
		List<Map<String,Object>> resultList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(list)){
			for(Map<String,Object> dMap : list){
				String tableName = MapUtils.getString(dMap,"DTableName");
				String remark1 = MapUtils.getString(dMap,"Remark","");
				if(type.equals(tableName) && remark1.equals(remark)){
					resultList.add(dMap);
				}
			}
		}
		return resultList;
	}

	@Override
	public Integer filterDictionaryList(List<Map<String,Object>> list, String dValue) {
		if(CollectionUtils.isNotEmpty(list)){
			for(Map<String,Object> dMap : list){
				String value = MapUtils.getString(dMap,"DValue");
				if(value.equals(dValue)){
					return MapUtils.getInteger(dMap,"DInt");
				}
			}
		}
		return null;
	}

	private List<Map<String, Object>> getAllDictionaryList() {
		List<Map<String, Object>> dictionaryList = (List<Map<String, Object>>) redisClientUtils.getObject("dictionaryList");
		if (CollectionUtils.isEmpty(dictionaryList)) {
			//放入redis中
			dictionaryList = dictionariesTDao.getAllDictionaries();
			redisClientUtils.setObject("dictionaryList", dictionaryList, 300);
		}
		return dictionaryList;
	}

	@Override
	public JSONArray getDictionaryTree(String dTableName) {
		//获取树状图的字典项
		List<Map<String, Object>> listByDTableName = dictionariesTDao.getDictionariesListByDTableName(dTableName);
		//获取 字典项里面其他的属性
		List<Map<String, Object>> listByDTableNameRequired = dictionariesTDao.getDictionariesListByDTableName(dTableName+REQUIRED);
		//树状图排序
		listByDTableName.sort((e1, e2) -> MapUtils.getInteger(e1, "DInt").compareTo(MapUtils.getInteger(e2, "DInt")));
		DictionariesTree dictionariesTree;
		List<DictionariesTree> treeList = new ArrayList<>();
		for (Map<String, Object> dMap : listByDTableName) {
			dictionariesTree = new DictionariesTree();
			dictionariesTree.setID(MapUtils.getLong(dMap, "ID"));
			dictionariesTree.setDInt(MapUtils.getInteger(dMap, "DInt"));
			dictionariesTree.setDValue(MapUtils.getString(dMap, "DValue"));
			dictionariesTree.setRemark(MapUtils.getString(dMap, "Remark"));
			if (CollectionUtils.isNotEmpty(listByDTableNameRequired)) {
				Map<Object, Object> requiredCollect = listByDTableNameRequired.stream().collect(Collectors.toMap(e1 -> e1.get("DValue"), e2 -> e2.get("Remark")));
				if (requiredCollect.containsKey(MapUtils.getString(dMap, "DValue"))) {
					if (StringUtils.isNotBlank(MapUtils.getString(requiredCollect,MapUtils.getString(dMap, "DValue")))) {
						com.alibaba.fastjson.JSONObject remarkData = com.alibaba.fastjson.JSONObject.parseObject(MapUtils.getString(requiredCollect,MapUtils.getString(dMap, "DValue")));
						dictionariesTree.setData(remarkData);
					}
				}
			}
			treeList.add(dictionariesTree);
		}
		treeList = TreeUtils.generateTrees(treeList);
		return JSONArray.parseArray(JSON.toJSONString(treeList, SerializerFeature.WriteMapNullValue));
	}
}
